#include "servicecenter.h"

#include <QCoreApplication>
#include <QDebug>
#include <QProcess>

ServiceCenter::ServiceCenter(QObject *parent)
    : QObject{parent}
{
    QProcess process;
    QString cmd = QCoreApplication::applicationDirPath() + "/bin/emqx.cmd";
    process.start(cmd, {"start"});
    if (!process.waitForStarted())
    {
        qCritical() << "Failed to start emqx.cmd: " << process.errorString();
    }
    else
    {
        if (process.waitForFinished(5000))
        {
            QString out = QString::fromLocal8Bit(process.readAllStandardOutput());
            QString err = QString::fromLocal8Bit(process.readAllStandardError());
            // qDebug() << "start output: " << out;
            if (!err.isEmpty())
            {
                qCritical() << "start error: " << err;
            }
        }
        else
        {
            process.kill();
            qCritical() << "start timeout: ";
        }
    }
}

ServiceCenter::~ServiceCenter()
{
    QProcess process;
    QString cmd = QCoreApplication::applicationDirPath() + "/bin/emqx.cmd";
    process.start(cmd, {"stop"});
    if (!process.waitForStarted())
    {
        qCritical() << "Failed to start emqx.cmd: " << process.errorString();
    }
    else
    {
        if (process.waitForFinished(5000))
        {
            QString out = QString::fromLocal8Bit(process.readAllStandardOutput());
            QString err = QString::fromLocal8Bit(process.readAllStandardError());
            // qDebug() << "start output: " << out;
            if (!err.isEmpty())
            {
                qCritical() << "start error: " << err;
            }
        }
        else
        {
            process.kill();
            qCritical() << "start timeout: ";
        }
    }
}
